package servlets.games;

import hibernate.method.GameCategoryMethods;
import hibernate.method.GameMethods;
import hibernate.model.Game;
import hibernate.util.HibernateUtil;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 * Servlet implementation class editGame
 */
@WebServlet("/editGame")

@MultipartConfig(maxFileSize = 16177215)
public class editGame extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public editGame() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		String game = (String) request.getParameter("game_id");
		int game_id = Integer.parseInt(game);
		String description = (String) request.getParameter("description");
		String users_min = (String) request.getParameter("users_min");
		String users_max = (String) request.getParameter("users_max");
		String [] category = request.getParameterValues("categories");
		InputStream inputStream = null;
		
		SessionFactory sessionFactory = HibernateUtil
				.getSessionAnnotationFactory();
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		GameMethods gm = new GameMethods();
		GameCategoryMethods gcatm = new GameCategoryMethods();
		Game g = gm.idToGame(sessionFactory, session, game_id);
		
		if(users_min != String.valueOf(g.getUsers_min()) || users_min !=null || String.valueOf(users_min).length()>0|| String.valueOf(users_min) !="" ){
			g.setUsers_min(Integer.parseInt(users_min));
		}
		if(users_max != String.valueOf(g.getUsers_max()) || users_max != null|| String.valueOf(users_max).length()>0 || String.valueOf(users_max) !="" ){
			g.setUsers_max(Integer.parseInt(users_max));
		}
		if(description != g.getDescribe() || description != null || String.valueOf(description).length()>0 || description !="" ){
			g.setDescribe(description);
		}

		if(category != null){
		for(int i=0;i<category.length;i++)
	        gcatm.addCategoryToGame(sessionFactory, session, game_id, Integer.parseInt(category[i]));
		}
		try {
			String dbURL = "jdbc:mysql://localhost:3306/thesis";
			String dbUser = "root";
			String dbPass = "";

			Connection conn = null;	
			DriverManager.registerDriver(new com.mysql.jdbc.Driver());
			conn = DriverManager.getConnection(dbURL, dbUser, dbPass);
			
			
		
		Part filePart = request.getPart("avatar");
		if (filePart != null) {
			System.out.println(filePart.getName());
			System.out.println(filePart.getSize());
			System.out.println(filePart.getContentType());
			
			inputStream = filePart.getInputStream();
		}
		
		if (inputStream  !=null && filePart.getSize()>0){
			String sql1 = "DELETE FROM gamesavatars WHERE game_id = ?";
			PreparedStatement stat1 = conn.prepareStatement(sql1);
			stat1.setLong(1,  game_id);
			stat1.execute();
			
			String sql = "INSERT INTO gamesavatars (game_id, avatar) values (?, ?)";
			PreparedStatement statement = conn.prepareStatement(sql);
			statement.setLong(1, game_id);
			statement.setBlob(2, inputStream);
			statement.executeUpdate();
		}
		
			session.getTransaction().commit();
			 out.println("<script type=\"text/javascript\">alert(\"Gra zostala zedytowana pomyslnie\"); window.location.href = \"social/index.jsp?page=games&group=searchGame\";</script>");
	    	
		} catch (Exception e) {
			 out.println("<script type=\"text/javascript\">alert(\"Gra nie zostala zedytowana\"); window.location.href = \"social/index.jsp?page=games&group=searchGame\";</script>");
		}
	}

}
